/**********************************************************************

 .-') _   _  .-')                         ('-.     _   .-')
(  OO) ) ( \( -O )                       ( OO ).-.( '.( OO )_
/     '._ ,------.  ,-.-')   ,----.      / . --. / ,--.   ,--.) ,-.-')
|'--...__)|   /`. ' |  |OO) '  .-./-')   | \-.  \  |   `.'   |  |  |OO)
'--.  .--'|  /  | | |  |  \ |  |_( O- ).-'-'  |  | |         |  |  |  \
   |  |   |  |_.' | |  |(_/ |  | .--, \ \| |_.'  | |  |'.'|  |  |  |(_/
   |  |   |  .  '.',|  |_.'(|  | '. (_/  |  .-.  | |  |   |  | ,|  |_.'
   |  |   |  |\  \(_|  |    |  '--'  |   |  | |  | |  |   |  |(_|  |
   `--'   `--' '--' `--'     `------'    `--' `--' `--'   `--'  `--'


*********************************************************************/

#include <iostream>
#include <stdlib.h>
#include <vector>

#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"
#include "CEGUI.h"
#include "RendererModules/OpenGL/ceguiopengl.h"

#include "include/Turret.h"
#include "include/Position.h"
#include "include/Minion.h"
#include "include/main.h"
#include "include/camera.h"
#include "include/interface.h"
#include "include/Hero.h"
#include "include/Global.h"
#include "include/SDLTimer.h"

using namespace std;

///////////////////////Variables//////////////////////////////
Mode GameMode = GamePlay;

//Event handler
SDL_Event event;
SDLTimer minionSpawner;
int miniondelay = 0;
Position SpawnPoint(8,-10);
Minion Spawner(SpawnPoint); // Spawnpoint for all the minions.
//Screen surface (used for resize)
SDL_Surface *surf;

//Quit variable for entire game
bool quit = false;

HeroState heroState = Walking;
InputType Input = None;
bool CheckBuildPos = false;
bool CheckBuildTimer = false;
Hero hero( Position(6,4)  );
Turret ShadowTurret( Position(0,0));
Turret SlowShadowTurret( Position(0,0),Slow);
Turret AoEShadowTurret(Position(0,0), AoE);
//Minion TestMinion ( Position(0,-10)); //used to test for walling off minion paths and if minion path chages due to turret placement
vector<Position> testPath; // Path vector used for TestMinion
std::vector<Turret> turret;
std::vector<Minion> Min;
std::vector<Position>TurPos;
vector<Position> heroSpawnPath;

bool CanBuild;
int _scrWidth = 0;
int _scrHeight = 0;
int _scrRatio = 0;
camera gameCamera(0,5,-17.0f,10);
int _x = 0;
int _y = 0;
const double _PI = 3.141529265;
float _angle = 30.0f;
///////////////////////End Variables//////////////////////////

///////////////////////Fuction Defines////////////////////////
void handleResize(GLsizei,GLsizei);
void AddMinion();
void gamePlay();
void game();
void clean_up();
////////////////////End Function Defines//////////////////////

////////////////////////Functions/////////////////////////////

//handleEvents() - main event handler for game
void handleEvents()
{
        handleKeypress();
        mouse(_x,_y);
           //While there are events to handle
		while( SDL_PollEvent( &event ) )
		{
            switch(event.type)
            {
            case SDL_QUIT:
                quit = true;
                break;
            case SDL_VIDEORESIZE:
                SDL_FreeSurface(surf);
                _scrWidth = event.resize.w;
                _scrHeight = _scrWidth/_scrRatio;
                surf = SDL_SetVideoMode(_scrWidth,_scrHeight,SCREEN_BPP,SDL_OPENGL|SDL_RESIZABLE);
                handleResize(_scrWidth,_scrHeight);
                break;
            case SDL_MOUSEMOTION:
                _x = event.motion.x;
                _y = event.motion.y;
                break;
            default:
                break;
        }

    }


}

//Initializes 3D rendering
void initRendering()
{
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_COLOR_MATERIAL);
    glEnable(GL_LIGHTING); //Enable lighting
    glEnable(GL_LIGHT0); //Enable light #0
    glEnable(GL_LIGHT1); //Enable light #1
    glEnable(GL_NORMALIZE); //Automatically normalize normals
    //glShadeModel(GL_SMOOTH); //Enable smooth shading
    glEnable (GL_BLEND);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

//Called when the window is resized
void handleResize(GLsizei w,GLsizei h)
{
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0, (double)w / (double)h, 1.0, 200.0);
    gameCamera.setScreenRatio(w,h);
}

//Draws the 3D scene
void drawScene()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    gameCamera.CamUpdate(_x,_y);

    // Initialize the names stack for picking
    glInitNames();
    glPushName(nGROUND);

    //Add ambient light
    GLfloat ambientColor[] = {0.2f, 0.2f, 0.2f, 1.0f}; //Color (0.2, 0.2, 0.2)
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);

    //Add positioned light
    GLfloat lightColor0[] = {0.5f, 0.5f, 0.5f, 1.0f}; //Color (0.5, 0.5, 0.5)
    GLfloat lightPos0[] = {4.0f, 0.0f, 8.0f, 1.0f}; //Positioned at (4, 0, 8)
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);

    //Add directed light
    GLfloat lightColor1[] = {0.5f, 0.2f, 0.2f, 1.0f}; //Color (0.5, 0.2, 0.2)
    //Coming from the direction (-1, 0.5, 0.5)
    GLfloat lightPos1[] = {-1.0f, 0.5f, 0.5f, 0.0f};
    glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1);
    glLightfv(GL_LIGHT1, GL_POSITION, lightPos1);

    glRotatef(-5, 1.0f, 0.0f, 0.0f);

    glBegin(GL_QUADS);
    glColor3f(0.2f, 0.4f, 0.4f);
    //Bottom
    glNormal3f(-1.0f, 0.0f, 0.0f);
    //glNormal3f(-1.0f, 0.0f, -1.0f);
    glVertex3f(-9.0f, -11.0f, GROUND);
    //glNormal3f(-1.0f, 0.0f, 1.0f);
    glVertex3f(9.0f, -11.0f, GROUND);
    //glNormal3f(-1.0f, 0.0f, 1.0f);
    glVertex3f(9.0f, 10.0f, GROUND);
    //glNormal3f(-1.0f, 0.0f, -1.0f);
    glVertex3f(-9.0f, 10.0f, GROUND);

    glEnd();

    for(int i = 0; i < Min.size(); i++){
        if(gameCamera.IsInBounds(Min[i].getPos(),GROUND)){
        Min[i].Draw();
        }
    }

    hero.Draw();
    hero.AutoFireAt(Min);
    hero.SkillTarget(Input);

    DrawShadowTurrets();
    hero.Skill(Min);
    for(int i = 0; i < turret.size(); i++){
        if(gameCamera.IsInBounds(turret[i].getPos(),GROUND)){
        turret[i].draw();
        }
        turret[i].FireAt(Min);
    }

    hero.drawTimer();
    SDL_GL_SwapBuffers();
}

//Handles drawing of shadow turrets
void DrawShadowTurrets()
{

    switch(Input)
    {
    case BuildStandard:
    {
        ShadowTurret.setPos( Position(roundf(getClickPos(_x, _y).Xpos),roundf(getClickPos(_x, _y).Ypos)));
        if(CheckObstruction(ShadowTurret.getPos()) || CheckWall(ShadowTurret.getPos()))
        {
            CanBuild = false;
            ShadowTurret.setColor(0.8,0,0);
        }
        else
        {
            CanBuild = true;
            ShadowTurret.setColor(0,0.9,0);
        }
        ShadowTurret.draw();
        glPushMatrix();
        glTranslatef(0,0,0.2);
        glColor4f(0,0.3,0.4,0.5);
        glBegin(GL_TRIANGLE_FAN);
        glVertex2f(ShadowTurret.getPos().Xpos, ShadowTurret.getPos().Ypos);
        for (int angle = 0; angle <= 360; angle+= 5)
            glVertex2f(ShadowTurret.getPos().Xpos + sin(angle*_PI/180) * ShadowTurret.GetRange(), ShadowTurret.getPos().Ypos + cos(angle*_PI/180) * ShadowTurret.GetRange());
        glEnd();
        glPopMatrix();
        break;
    }
    case BuildSlow:
    {
        SlowShadowTurret.setPos( Position(roundf(getClickPos(_x, _y).Xpos),roundf(getClickPos(_x, _y).Ypos)));
        if(CheckObstruction(SlowShadowTurret.getPos()) || CheckWall(SlowShadowTurret.getPos()))
        {

            CanBuild = false;
            SlowShadowTurret.setColor(0.8,0,0);
        }
        else
        {
            CanBuild = true;

            SlowShadowTurret.setColor(0,0.9,0);
        }
        SlowShadowTurret.draw();
        glPushMatrix();
        glTranslatef(0,0,0.2);
        glColor4f(0,0.3,0.4,0.5);
        glBegin(GL_TRIANGLE_FAN);
        glVertex2f(SlowShadowTurret.getPos().Xpos, SlowShadowTurret.getPos().Ypos);
        for (int angle = 0; angle <= 360; angle+= 5)
            glVertex2f(SlowShadowTurret.getPos().Xpos + sin(angle*_PI/180) * SlowShadowTurret.GetRange(), SlowShadowTurret.getPos().Ypos + cos(angle*_PI/180) * SlowShadowTurret.GetRange());
        glEnd();
        glPopMatrix();
        break;
    }
      case BuildAoE:
    {
        AoEShadowTurret.setPos( Position(roundf(getClickPos(_x, _y).Xpos),roundf(getClickPos(_x, _y).Ypos)));
        if(CheckObstruction(AoEShadowTurret.getPos()) || CheckWall(AoEShadowTurret.getPos()))
        {

            CanBuild = false;
            AoEShadowTurret.setColor(0.8,0,0);
        }
        else
        {
            CanBuild = true;

            AoEShadowTurret.setColor(0,0.9,0);
        }
        AoEShadowTurret.draw();
        glPushMatrix();
        glTranslatef(0,0,0.2);
        glColor4f(0,0.3,0.4,0.5);
        glBegin(GL_TRIANGLE_FAN);
        glVertex2f(AoEShadowTurret.getPos().Xpos, AoEShadowTurret.getPos().Ypos);
        for (int angle = 0; angle <= 360; angle+= 5)
            glVertex2f(AoEShadowTurret.getPos().Xpos + sin(angle*_PI/180) * AoEShadowTurret.GetRange(), AoEShadowTurret.getPos().Ypos + cos(angle*_PI/180) * AoEShadowTurret.GetRange());
        glEnd();
        glPopMatrix();
        break;
    }
    }
}



//Contains update for minion, and hero functions
void update()
{
    AddMinion();
    for(int i = 0; i < Min.size(); i++)
    {
        Min[i].Update();
        if(Min[i].getPos() == Min[i].GetGoal())
            Min.erase(Min.begin() + i);
    }
    hero.Update();

    if(CheckBuildPos) //checks to see if the hero is in position to build a turret, if so, it will start building
    {
        if(hero.getPos() == hero.GetGoal())
        {
            hero.beginBuild();
            heroState = Building;
            CheckBuildTimer = true;
            CheckBuildPos = false;
        }
    }
    if(CheckBuildTimer) //Tests to see if the timer for the building is done, if so, it places the turret.
    {
        if(hero.checkBuildTimer(1))
        {
         BuildTurret(hero.getPos());
         CheckBuildTimer = false;
        }
    }
}

void AddMinion()
{
    //glutPostRedisplay();
    if(!minionSpawner.is_started())
        minionSpawner.start();
    if(minionSpawner.get_ticks() > 10000) //10000ms = 10s, minions will spawn every 10 seconds
    {


        //minionSpawner.stop();
        if(miniondelay >= 6){
        minionSpawner.start();
        miniondelay = 0;
        }
        if(minionSpawner.get_ticks() - 10000 - miniondelay*200 > 0){
            miniondelay++;
        Min.push_back(Minion(  Spawner.getPos()));
        Min[Min.size() - 1].SetIndex(Min.size() - 1);
        Min[Min.size()-1].setPath(Spawner.getBestPath());
        }
    }
}

//SDL and other Initialization junk
bool init()
{
    _scrWidth = 640*2;
    _scrHeight = 320*2;
    _scrRatio = _scrWidth/_scrHeight;
    //Initialize SDL
    if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
    {
        return false;
    }
    freopen( "CON", "w", stdout );
    freopen( "CON", "w", stderr );
    //Create Window
    if( (surf = SDL_SetVideoMode( _scrWidth, _scrHeight, SCREEN_BPP, SDL_OPENGL | SDL_RESIZABLE )) == NULL )
    {
        return false;
    }
    handleResize(_scrWidth,_scrHeight);
    initRendering();
    //Set caption
    SDL_WM_SetCaption( "Tower God", NULL );

    return true;
}

void game()
{
	// find out which game mode we are in and call the appropiate routine
	switch ( GameMode )
	{
	// the game itself!
	case GamePlay:
		gamePlay();
		break;
	}
}

//Function of the actual game!
void gamePlay()
{
    update();
    handleEvents();
    drawScene();
}

void drawWalls()
{
    //Bound on the down
    for(int k = -9; k <= 9; k++){
    turret.push_back( Turret( Position(k,-11),Wall) ); //Bottom walls
    turret[turret.size() - 1].SetIndex(turret.size() - 1);
    }

    for(int k = -10; k <= 9; k++){
    turret.push_back( Turret( Position(9,k),Wall) ); // Right walls
    turret[turret.size() - 1].SetIndex(turret.size() - 1);
    }

    for(int k = -10; k <= 9; k++){
    turret.push_back( Turret( Position(-9,k),Wall) ); // Left walls
    turret[turret.size() - 1].SetIndex(turret.size() - 1);
    }

    for(int i=0; i < turret.size(); i++)
    {
        TurPos.push_back(turret[i].getPos());
    }
}

int main(int argc, char** argv)
{

    CEGUI::OpenGLRenderer* myRenderer = new CEGUI::OpenGLRenderer( 0 );
    new CEGUI::System(renderer);

    //Initialize
    if( init() == false )
    {
        return 1;
    }

    drawWalls();
    //The frame rate regulator
    SDLTimer fps;
    Spawner.bestPath(TurPos, goal);
    hero.ModifyColor(0,0.8,0);

   fps.start();

	//Wait for user exit
	while( quit == false )
	{
        //Start the frame timer
        if( fps.get_ticks() < 1000 / FRAMES_PER_SECOND )
        {
            SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() );
        }
        game();
	}

	//Clean up
	clean_up();

	return 0;
}

void clean_up()
{
    //Quit SDL
    SDL_Quit();
}


